<template>
  <div class="rank-page" :class="{ 'slide-in': isVisible }">
    <div class="header">
      <van-icon name="arrow-left" class="back-icon" @click="handleBack" />
      <span class="title">排行榜</span>
    </div>

    <div class="tabs">
      <div v-for="tab in tabs" :key="tab.value" class="tab-item" :class="{ active: currentTab === tab.value }"
        @click="handleTabChange(tab.value)">
        {{ tab.label }}
      </div>
    </div>

    <div class="content">
      <van-loading v-if="loading" class="loading" type="spinner" color="#1989fa" />

      <div v-else-if="rankList.length === 0" class="empty-state">
        <van-empty description="暂无排行榜数据" />
      </div>

      <div v-else class="rank-list">
        <div v-for="(item, index) in rankList" :key="item.id || index" class="rank-item" @click="handleItemClick(item)">
          <div class="thumbnail-container">
            <img :src="item.cover?.feed || getDefaultCover()" :alt="item.title" class="thumbnail" />
            <div class="rank-badge" :class="`rank-${index + 1}`">
              No.{{ index + 1 }}
            </div>
            <div v-if="item.duration" class="duration-badge">
              {{ formatDuration(item.duration) }}
            </div>
          </div>

          <div class="info">
            <div class="title">{{ item.title }}</div>
            <div class="author">UP {{ item.author?.name }}</div>
            <div class="stats">
              <span>
                <van-icon name="good-job-o" size="12" />
                {{ formatCount(item.consumption?.collectionCount || 0) }}
              </span>
              <span>
                <van-icon name="chat-o" size="12" />
                {{ formatCount(item.consumption?.replyCount || 0) }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import { getRankList } from '@/api/api'
import { useVideoStore } from '@/stores/counter'

const router = useRouter()
const videoStore = useVideoStore()

const isVisible = ref(false)
const loading = ref(false)
const currentTab = ref<'weekly' | 'monthly' | 'historical'>('weekly')
const rankList = ref<any[]>([])

const tabs = [
  { label: '周排行榜', value: 'weekly' as const },
  { label: '月排行榜', value: 'monthly' as const },
  { label: '总排行榜', value: 'historical' as const }
]

// 格式化时长
const formatDuration = (seconds: number): string => {
  if (!seconds) return '00:00'
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}

// 格式化数字
const formatCount = (count: number): string => {
  if (!count) return '0'
  if (count >= 10000) return `${(count / 10000).toFixed(1)}万`
  return count.toString()
}

// 获取默认封面
const getDefaultCover = (): string => {
  return ''
}

// 处理返回
const handleBack = () => {
  // 触发退出动画
  isVisible.value = false
  // 等待动画完成后再路由返回
  setTimeout(() => {
    router.back()
  }, 300)
}

// 处理标签切换
const handleTabChange = (tab: 'weekly' | 'monthly' | 'historical') => {
  if (currentTab.value === tab) return
  currentTab.value = tab
  fetchRankList()
}

// 处理点击视频项
const handleItemClick = (item: any) => {
  // 设置当前视频并跳转
  videoStore.setCurrentVideo({
    id: item.id,
    title: item.title,
    description: item.description,
    playUrl: item.playUrl,
    cover: item.cover,
    author: item.author,
    duration: item.duration,
    tags: item.tags,
    consumption: item.consumption
  })

  router.push(`/video/${item.id}`)
}

// 获取排行榜数据
const fetchRankList = async () => {
  loading.value = true
  try {
    const data: any = await getRankList(currentTab.value)
    if (data.itemList && data.itemList.length > 0) {
      // 提取视频数据
      rankList.value = []
      data.itemList.forEach((item: any) => {
        if (item.type === 'video') {
          rankList.value.push(item.data)
        }
      })
    } else {
      rankList.value = []
    }
  } catch (err) {
    console.error('获取排行榜失败:', err)
    rankList.value = []
  } finally {
    loading.value = false
  }
}

// 初始化动画
const initAnimation = () => {
  // 确保初始状态是隐藏的（translateX(100%)）
  isVisible.value = false

  // 延迟一帧确保DOM已渲染，然后触发进入动画
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      isVisible.value = true
    })
  })
}

// 组件挂载时初始化（处理组件未被 keep-alive 缓存的情况）
onMounted(() => {
  // 初始化动画
  initAnimation()
  // 加载数据
  fetchRankList()
})

// keep-alive 组件激活时重新加载数据（处理组件被缓存的情况）
// 注意：如果组件被 keep-alive 缓存，onActivated 会在 onMounted 之后执行
// 如果组件未被缓存，onActivated 不会执行，所以需要在 onMounted 中也加载数据
onActivated(() => {
  // 每次组件激活时都重新加载数据，确保数据是最新的
  // 这是解决跳转后数据不显示问题的关键
  fetchRankList()

  // 如果组件还没有显示（比如从其他页面返回时），重新初始化动画
  if (!isVisible.value) {
    initAnimation()
  }
})

onUnmounted(() => {
  isVisible.value = false
})
</script>

<style scoped lang="less">
.rank-page {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  transform: translateX(100%);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  flex-direction: column;
  overflow: hidden;

  &.slide-in {
    transform: translateX(0);
  }

  .header {
    width: 100%;
    height: 6vh;
    padding: 0 4vw;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    gap: 3vw;
    border-bottom: 1px solid #f5f5f5;
    position: sticky;
    top: 0;
    background-color: #fff;
    z-index: 10;

    .back-icon {
      font-size: 18px;
      color: #333;
      cursor: pointer;
    }

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }
  }

  .tabs {
    display: flex;
    align-items: center;
    padding: 0 4vw;
    background-color: #fff;
    border-bottom: 1px solid #f5f5f5;
    position: sticky;
    top: 6vh;
    z-index: 10;

    .tab-item {
      flex: 1;
      height: 5vh;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      color: #666;
      cursor: pointer;
      transition: color 0.2s;
      position: relative;

      &.active {
        color: #1989fa;
        font-weight: 500;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 30px;
          height: 2px;
          background-color: #1989fa;
        }
      }

      &:active {
        opacity: 0.6;
      }
    }
  }

  .content {
    flex: 1;
    width: 100%;
    overflow-y: auto;
    padding: 2vh 4vw;
    box-sizing: border-box;
    padding-bottom: 10vh;

    .loading {
      display: flex;
      justify-content: center;
      padding: 4vh 0;
    }

    .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 60vh;
    }

    .rank-list {
      display: flex;
      flex-direction: column;
      gap: 3vh;

      .rank-item {
        display: flex;
        gap: 3vw;
        cursor: pointer;
        transition: background-color 0.2s;
        padding: 1vh 0;
        border-radius: 8px;
        align-items: center;

        &:active {
          background-color: #f9f9f9;
        }

        .thumbnail-container {
          position: relative;
          width: 35vw;
          aspect-ratio: 16 / 9;
          border-radius: 8px;
          overflow: hidden;
          flex-shrink: 0;
          background-color: #f5f5f5;

          .thumbnail {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .rank-badge {
            position: absolute;
            top: 0;
            left: 0;
            padding: 4px 8px;
            font-size: 12px;
            font-weight: 600;
            color: #fff;
            border-bottom-right-radius: 4px;
            border-top-left-radius: 4px;
            z-index: 2;
            background-color: #999;

            &.rank-1 {
              background-color: #ff6b6b;
            }

            &.rank-2 {
              background-color: #ffa726;
            }

            &.rank-3 {
              background-color: #ffca28;
            }
          }

          .duration-badge {
            position: absolute;
            bottom: 4px;
            right: 4px;
            background-color: rgba(0, 0, 0, 0.6);
            color: #fff;
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 4px;
            z-index: 2;
          }
        }

        .info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          min-width: 0;
          padding: 0.5vh 0;

          .title {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-bottom: 1vh;
          }

          .author {
            font-size: 12px;
            color: #999;
            margin-bottom: 0.5vh;
          }

          .stats {
            display: flex;
            align-items: center;
            gap: 2vw;
            font-size: 11px;
            color: #999;

            span {
              display: flex;
              align-items: center;
              gap: 2px;
            }
          }
        }
      }
    }
  }
}
</style>
